﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using QLNhaThuoc.DTO;
using NCalc;

namespace QLNhaThuoc.DAL
{
    public abstract class MappingDA
    {
        protected MappingDTO mapping = new MappingDTO();

        protected XmlDocument _xmlDocument;
        protected XmlElement _xmlRoot;


        public MappingDA()
        {
            _xmlDocument = new XmlDocument();
        }

        public void layDuLieuTuXML(string tenFile)
        {
            _xmlDocument.Load(tenFile);
            _xmlRoot = _xmlDocument.DocumentElement;
            XmlNodeList xmlChilds = _xmlRoot.ChildNodes;

            mapping.Data.Clear();
            mapping.Name.Clear();

            foreach (XmlAttribute attr in xmlChilds[0].Attributes)
            {
                mapping.Name.Add(attr.Name);
            }

            foreach (XmlNode xmlChild in xmlChilds)
            {
                List<string> data = new List<string>();
                foreach (XmlAttribute attr in xmlChild.Attributes)
                {
                    data.Add(attr.InnerText);
                }

                mapping.Data.Add(data);
            }
        }

        public List<string> layThuocTinh()
        {
            return mapping.Name;
        }

        public List<List<string>> layDuLieu()
        {
            return mapping.Data;
        }

        public virtual string mappingXMLToDB(List<ExpressionDTO> dataExpression)
        {
            return "";
        }

        public int exists(string name, List<ExpressionDTO> dataExp)
        {
            for (int i = 0; i < dataExp.Count; i++ )
            {
                if (dataExp[i].Name.CompareTo(name) == 0)
                {
                    return i;
                }
            } 

            return -1;
        }

        public string returnEvaluated(int index, ExpressionDTO _exp)
        {
            Expression exp = new Expression(_exp.Expression);

            foreach (string parameter in _exp.Parameters)
            {
                exp.Parameters[parameter] = returnValue(index, parameter);
            }

            return exp.Evaluate().ToString();
        }

        public string returnValue(int index, string name)
        {
            for (int i = 0; i < mapping.Name.Count; i++)
            {
                if (mapping.Name[i].CompareTo(name) == 0)
                {
                    return mapping.Data[index][i];
                }
            }

            return string.Empty;
        }
    }
}
